package com.zbw.printlibrary.printSub;

import android.content.Context;
import android.graphics.Bitmap;

import androidx.annotation.NonNull;
import com.posin.device.Printer;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.BitmapUtil;
import com.zbw.printlibrary.util.PrintThreadPoolManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 宝盈打印机
 */
public class PrintPosIn extends PrinterControlCommon {
    // 宝盈打印
    private Printer prt = null;
    private Context mContext;
    private IPrintCallBack mCallBack;
    //居中
    private final byte[] CMD_ALIGN_CENTER = {0x1B, 0x61, 1};
    //左对齐
    private final byte[] CMD_ALIGN_LEFT = {0x1B, 0x61, 0};
    //打印机初始化
    private final byte[] CMD_INIT = {27, 64};
    //字体倍宽
    private final byte[] CMD_ZIFU_BEI_KUAN = {0x1B, 0x21, 0x32};
    //字体倍高宽
    private final byte[] CMD_BEI_GAOKUAN = {0x1C, 0x21, 0x0c};
    //汉字初始化
    private static final byte[] CMD_HANZI_INIT = {0x1C, 0x21, 0x0};
    //字符初始化
    private static final byte[] CMD_ZIFU_INIT = {0x1B, 0x21, 0x0};
    //切纸
    private final byte[] CMD_CUT = {'\n', '\n', '\n', '\n', 0x1D, 0x56, 1};


    public PrintPosIn(@NonNull Context context, IPrintCallBack callback) {
        mContext = context;
        this.mCallBack = callback;
    }

    @Override
    public void connectPrinter() {
        try {
            prt = Printer.newInstance();
            if (!prt.ready()) {
                return;
            }
            mCallBack.onConnect("连接成功", true);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @Override
    public void disConnectPrinter() {
        if (prt != null) {
            prt.close();
        }
    }

    @Override
    public void printTest(List<String> testList) {
        final List<byte[]> bytes = getListBytePrint(testList);
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < bytes.size(); i++) {
                        prt.getOutputStream().write(bytes.get(i));
                    }
                    mCallBack.onPrintResult(true);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    mCallBack.onPrintResult(false);
                }
            }
        });
    }

    @Override
    public void printString(List<AttributeBean> testList) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            //初始化
            out.write(CMD_INIT);
            for (int i = 0; i < testList.size(); i++) {
                String msg = testList.get(i).getContext();
                if (testList.get(i).getFont_size() == 0) {
                    out.write(CMD_ZIFU_INIT);
                    out.write(CMD_HANZI_INIT);
                } else {
                    out.write(CMD_ZIFU_BEI_KUAN);
                    out.write(CMD_BEI_GAOKUAN);
                }

                if (testList.get(i).getFont_gray() == 1) {
                    out.write(CMD_ALIGN_CENTER);
                } else {
                    out.write(CMD_ALIGN_LEFT);
                }
                String line = "";
                if (testList.get(i).isFont_line()) {
                    line = "\n";
                }
                if (1 == testList.get(i).getContext_type()) {
                    Bitmap bitmap = testList.get(i).getBitmap();
                    out.write(BitmapUtil.genBitmapCode(bitmap));
                } else {
                    out.write((msg + line).getBytes("gb2312"));
                }
            }

            out.write(CMD_CUT);
            out.flush();
            //发送给打印机
            prt.getOutputStream().write(out.toByteArray());
            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void printStringAndBitmap(List<String> testList, LinkedHashMap<Integer, Bitmap> bitmapHashMap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            //初始化
            out.write(CMD_INIT);
            for (int i = 0; i < testList.size(); i++) {
                String msg = testList.get(i);
                switch (i) {
                    case 0:
                    case 1:
                        out.write(CMD_ZIFU_BEI_KUAN);
                        out.write(CMD_BEI_GAOKUAN);
                        out.write(CMD_ALIGN_CENTER);
                        out.write((msg + "\n").getBytes("gb2312"));
                        break;
                    default:
                        if (msg.startsWith("牌号")) {
                            out.write(CMD_ZIFU_BEI_KUAN);
                            out.write(CMD_BEI_GAOKUAN);
                            out.write(CMD_ALIGN_LEFT);
                            out.write((msg + "\n").getBytes("gb2312"));
                        } else {
                            out.write(CMD_ZIFU_INIT);
                            out.write(CMD_HANZI_INIT);
                            out.write(CMD_ALIGN_LEFT);
                            out.write((msg + "\n").getBytes("gb2312"));
                        }
                }
                Bitmap bitmap = bitmapHashMap.get(i);
                if (bitmap != null) {
                    //当前位置与需要打印图片位置一致 打印bitmap
                    out.write(CMD_ALIGN_CENTER);
                    out.write(BitmapUtil.genBitmapCode(bitmap));
                }
            }
            if (bitmapHashMap.size() > 0) {
                out.write(CMD_ALIGN_CENTER);
                //传入的position位置大于list的话默认在最后面打印
                for (Map.Entry<Integer, Bitmap> entry : bitmapHashMap.entrySet()) {
                    if (entry.getKey() > testList.size() - 1) {
                        Bitmap showBitmap = entry.getValue();
                        out.write(BitmapUtil.genBitmapCode(showBitmap));
                    }
                }
            }
            out.write(CMD_CUT);
            out.flush();
            //发送给打印机
            prt.getOutputStream().write(out.toByteArray());
            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 生成打印文本
     *
     * @return List<byte [ ]>
     */
    private List<byte[]> getListBytePrint(List<String> mList) {
        List<byte[]> mBytes = new ArrayList<>();
        // 打印机初始化
        byte[] CMD_INIT = {27, 64};
        mBytes.add(CMD_INIT);

        for (int i = 0; i < mList.size(); i++) {
            try {
                mBytes.add((mList.get(i) + "\n").getBytes("gb2312"));
            } catch (Exception e) {
            }
        }
        final byte[] CMD_CUT = {0x1D, 0x56, 0};
        mBytes.add(CMD_CUT);
        return mBytes;
    }


    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {
        prt = null;
        mCallBack.onDisConnect("断开成功", true);
    }

    @Override
    public void openMoneyBox() {

    }

    @Override
    public boolean isConnected() {
        if (prt == null) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
